//
//  FoodDetailsViewController.m
//  project_delicious
//
//  Created by dlios on 15-3-24.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "FoodDetailsViewController.h"
#import "TheFoodDetailsCell.h"
#import "MyCookingViewController.h"
#import "VideoOneViewController.h"

@interface FoodDetailsViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UIImageView *myFavorImageView;
@property (nonatomic, assign) BOOL flag;
@property (nonatomic, retain) NSString *hotWaterVideo;
@property (nonatomic, retain) MBProgressHUD *hud;
@end

@implementation FoodDetailsViewController

- (void)dealloc
{
    [_hud release];
    [_hotWaterVideo release];
    [_myFavorImageView release];
    [_str release];
    [_dic release];
    [super dealloc];
}
- (NSURL *)strChangeUrl:(NSString *)str
{
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    return url;
}
- (CGFloat)changeframe:(NSString *)str
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:10]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
    
}
//转菊花
- (void)mbHud
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    self.hud.labelText = @"Loading...";
    //self.hud.detailsLabelText = @"正在为您加载";
    [self.view addSubview:self.hud];
    [_hud release];
    [_hud show:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self mbHud];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"IMG_1345.JPG"]];

    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cook.png"] style:UIBarButtonItemStylePlain target:self action:@selector(barButtonAction:)] autorelease];
    
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64)];
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    [scrollView release];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSLog(@"________%@", self.str);
    [manager GET:self.str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = responseObject;
        self.arr = [self.dic objectForKey:@"TblSeasoning"];
        self.nameTitle = [self.dic objectForKey:@"name"];
        UIImageView *theImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 5, 5, self.view.bounds.size.width * 3 / 5, self.view.frame.size.height / 3)];
//        theImageView.contentMode = UIViewContentModeScaleAspectFit;
        theImageView.layer.cornerRadius = 10;
        theImageView.layer.masksToBounds = YES;
        NSString *str = [self.dic objectForKey:@"imageFilename"];
        [theImageView setImageWithURL:[self strChangeUrl:str]];
        [scrollView addSubview:theImageView];
        [theImageView release];
        
        NSString *heightsText = [self.dic objectForKey:@"materialPrepare"];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 15 + theImageView.frame.size.height + theImageView.frame.origin.y, self.view.bounds.size.width - 40, [self changeframe:heightsText])];
        label.text = [self.dic objectForKey:@"materialPrepare"];
//        label.frame = CGRectMake(20, 15 + scrollView.frame.size.height / 4, self.view.bounds.size.width - 40, [self changeframe:label.text]);
        label.numberOfLines = 0;
        [label sizeToFit];
        [scrollView addSubview:label];
        [label release];
        
        
        UIImageView *materialImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, label.frame.origin.y + label.frame.size.height + 20, self.view.bounds.size.width - 40, self.view.frame.size.height / 4)];
//        materialImageView.contentMode = UIViewContentModeScaleAspectFit;
        NSString *str1 = [self.dic objectForKey:@"materialImage"];
        [materialImageView setImageWithURL:[self strChangeUrl:str1]];
        [scrollView addSubview:materialImageView];
        [materialImageView release];
        
        NSString *heightText = [self.dic objectForKey:@"flavor"];
        
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(20, materialImageView.frame.origin.y + materialImageView.frame.size.height + 20, self.view.bounds.size.width - 40, [self changeframe:heightText])];
        label1.numberOfLines = 0;
        label1.text = [self.dic objectForKey:@"flavor"];
//        label1.frame = CGRectMake(20, materialImageView.frame.origin.y + materialImageView.frame.size.height + 20, self.view.bounds.size.width - 40, [self changeframe:label1.text]);
        [scrollView addSubview:label1];
        [label1 release];
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, label1.frame.origin.y + label1.frame.size.height + 20, self.view.bounds.size.width - 40, self.arr.count * (self.view.frame.size.height / 4)) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.scrollEnabled = NO;
        [scrollView addSubview:tableView];
        [tableView release];
        
        [tableView registerClass:[TheFoodDetailsCell class] forCellReuseIdentifier:@"guo"];
        scrollView.contentSize = CGSizeMake(self.view.frame.size.width, tableView.frame.origin.y + self.arr.count * self.view.frame.size.height / 4 + 10);
        
        self.title = self.nameTitle;
        
        self.hotWaterVideo = [self.dic objectForKey:@"hotwaterVideo"];
//        UIButton *buttonVideo = [UIButton buttonWithType:UIButtonTypeSystem];
//        buttonVideo.frame = CGRectMake(WIDTH - 50, 70, 50, 50);
//        [buttonVideo setTitle:@"视频" forState:UIControlStateNormal];
//        [buttonVideo addTarget:self action:@selector(buttonVideoAction:) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:buttonVideo];
        
        UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeSystem];
        buttonShare.frame = CGRectMake(WIDTH - 50, 150, 50, 50);
        [buttonShare setTitle:@"分享" forState:UIControlStateNormal];
        [buttonShare addTarget:self action:@selector(buttonShareAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:buttonShare];
        
        [_hud removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败");
    }];
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    button.frame = CGRectMake(WIDTH - 50, 0, 50, 50);
//    [button setTitle:@"收藏" forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
//    [self.view bringSubviewToFront:button];
    
    self.myFavorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH - 50, 0, 50, 50)];
    
    self.myFavorImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.myFavorImageView addGestureRecognizer:tap];
    [tap release];
    self.myFavorImageView.image = [UIImage imageNamed:@"favorite.png"];
    [self.view addSubview:self.myFavorImageView];
    [self.view bringSubviewToFront:self.myFavorImageView];
    [_myFavorImageView release];
    NSMutableArray *favArr = [NSMutableArray array];
    favArr = [[DataBaseHandler shareInstance] selectAll];
    Food *food = [[Food alloc] init];
    for (food in favArr) {
        if ([food.foodStr isEqualToString:self.str]) {
            self.myFavorImageView.image = [UIImage imageNamed:@"favorite2.png"];
            UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction2:)];
            [self.myFavorImageView addGestureRecognizer:tap2];
            [tap2 release];
        }
    }
    
}

- (UIImage *)imageFromView:(UIView *)theView
{
    UIGraphicsBeginImageContext(theView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext: context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
- (void)buttonShareAction:(UIButton *)button
{
    //    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    UIImage *shareimage =  [self imageFromView:self.view];
    NSURL *url = [NSURL URLWithString:self.str];
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"分享内容"
                                       defaultContent:@"测试一下"
                                                image:[ShareSDK pngImageWithImage:shareimage]
                                                title:@"美食"
                                                  url:self.str
                                          description:nil
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:button arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功" message:@"成功了哦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                                    [alertView show];
                                    [self.view addSubview:alertView];
                                    [alertView release];
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败了" message:@"再试一次" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                                    [alertView show];
                                    [self.view addSubview:alertView];
                                    [alertView release];
                                }

                            }];
}


- (void)buttonVideoAction:(UIButton *)button
{
    VideoOneViewController *video = [[VideoOneViewController alloc] init];
    video.strVideo1 = self.hotWaterVideo;
    
    [self.navigationController pushViewController:video animated:YES];
    [video release];
}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    Food *food = [[Food alloc] init];
    food.foodStr = self.str;
    food.nameLabel = self.nameTitle;
    if (self.flag == NO) {
        [[DataBaseHandler shareInstance] insertFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite2.png"];
    } else {
        NSLog(@"---%@", food.foodStr);
        [[DataBaseHandler shareInstance] deleteFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite.png"];
    }
    self.flag = !self.flag;
    
}
- (void)tapAction2:(UITapGestureRecognizer *)tap
{
    Food *food = [[Food alloc] init];
    food.foodStr = self.str;
    food.nameLabel = self.nameTitle;
    if (self.flag == NO) {
        NSLog(@"---%@", food.foodStr);
        [[DataBaseHandler shareInstance] deleteFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite.png"];
    } else {
        [[DataBaseHandler shareInstance] insertFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite2.png"];
    }
    self.flag = !self.flag;
    
}
//- (void)buttonAction:(UIButton *)button
//{
//    
//    Food *food = [[Food alloc] init];
//    food.foodStr = self.str;
//    food.nameLabel = self.nameTitle;
//    [[DataBaseHandler shareInstance] insertFood:food];
//    
//    NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
//    
//}

- (void)barButtonAction:(UIButton *)button
{
    MyCookingViewController *cook = [[MyCookingViewController alloc] init];
    cook.arr = [self.dic objectForKey:@"TblProcess"];
    [self.navigationController pushViewController:cook animated:YES];
    [cook release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TheFoodDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"guo"];
    NSString *str = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"imagePath"];
    [cell.foodImageView setImageWithURL:[self strChangeUrl:str]];
//    cell.foodImageView.contentMode = UIViewContentModeScaleAspectFit;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 4;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
